<script setup>
import { ref, onMounted, computed } from 'vue';
import { getAllDoctorsService, updateDoctorService, deleteDoctorService } from '@/api/admin.js';
import { getAllClinicsService, addDoctorService } from '@/api/hospital.js';
import { ElMessage, ElMessageBox, ElDialog } from 'element-plus';

// 定义医生列表数据
const doctors = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const totalDoctors = ref(0);
const searchQuery = ref('');
const clinics = ref([]);
const clinicsLoaded = ref(false);

// 定义对话框相关数据
const dialogVisible = ref(false);
const currentDoctor = ref({});
const dialogType = ref('update'); // 'update' 或 'add'

// 新增医生对话框相关数据
const addDialogVisible = ref(false);
const newDoctor = ref({
  name: '',
  gender: '',
  username: '',
  contactNumber: '',
  title: '',
  clinicId: ''
});

// 获取所有医生信息的函数
const fetchDoctors = async () => {
  try {
    const response = await getAllDoctorsService();
    if (response.code === 0) {
      doctors.value = response.data;
      totalDoctors.value = response.data.length;
    } else {
      ElMessage.error(response.message || '获取医生信息失败');
    }
  } catch (error) {
    ElMessage.error('获取医生信息失败');
  }
};

// 获取所有科室信息的函数
const fetchClinics = async () => {
  try {
    const response = await getAllClinicsService();
    if (response.code === 0) {
      clinics.value = response.data;
      clinicsLoaded.value = true;
    } else {
      ElMessage.error(response.message || '获取科室信息失败');
    }
  } catch (error) {
    ElMessage.error('获取科室信息失败');
  }
};

// 计算属性：根据用户名过滤医生列表
const filteredDoctors = computed(() => {
  if (!searchQuery.value) {
    return doctors.value;
  }
  return doctors.value.filter(doctor =>
    doctor.username.includes(searchQuery.value) ||
    doctor.name.includes(searchQuery.value)
  );
});

// 动态映射显示的医生数据（包含 clinicName）
const displayDoctors = computed(() => {
  return filteredDoctors.value.map(doctor => {
    const clinic = clinics.value.find(item => item.clinicId === doctor.clinicId) || { clinicName: '未知科室' };
    return {
      ...doctor,
      clinicName: clinic.clinicName
    };
  });
});

// 更新医生信息的函数
const updateDoctor = async (doctor) => {
  try {
    console.log('Current doctor data before update:', doctor); // 打印完整的医生对象
    // 传递完整的医生对象
    const doctorData = {
      id: doctor.id, // 医生ID
      doctorId: doctor.doctorId,
      username: doctor.username,
      name: doctor.name,
      gender: doctor.gender,
      title: doctor.title,
      contactNumber: doctor.contactNumber === null ? '' : doctor.contactNumber,
      clinicId: doctor.clinicId,
      email: doctor.email
    };
    // 增加一个console
    console.log(doctorData);
    const response = await updateDoctorService(doctorData);
    if (response.code === 0) {
      ElMessage.success('更新成功');
      await fetchDoctors(); // 确保重新获取医生列表
      await fetchClinics(); // 重新获取科室信息
      dialogVisible.value = false;
    } else {
      ElMessage.error(response.message || '更新失败');
    }
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

// 删除医生信息的函数
const deleteDoctor = async (doctorId) => {
  try {
    await ElMessageBox.confirm('确定要删除该医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const response = await deleteDoctorService(doctorId);
    if (response.code === 0) {
      ElMessage.success('删除成功');
      fetchDoctors();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 打开更新对话框
const openUpdateDialog = (doctor) => {
  currentDoctor.value = { ...doctor }; // 保证拿到-doctorId和名字
  dialogVisible.value = true;
};

// 打开新增对话框
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 新增医生信息的函数
const addDoctor = async () => {
  try {
    const response = await addDoctorService(newDoctor.value);
    if (response.code === 0) {
      ElMessage.success('新增成功');
      await fetchDoctors(); // 确保重新获取医生列表
      addDialogVisible.value = false;
      // 重置 newDoctor 对象
      newDoctor.value = {
        name: '',
        gender: '',
        username: '',
        contactNumber: '',
        title: '',
        clinicId: ''
      };
    } else {
      ElMessage.error(response.message || '新增失败');
    }
  } catch (error) {
    ElMessage.error('新增失败');
  }
};

// 在组件挂载时获取医生数据
onMounted(() => {
  fetchDoctors();
  fetchClinics();
});
</script>


<template>
  <div>
    <el-input
      v-model="searchQuery"
      placeholder="搜索医生姓名或用户名"
      style="margin-bottom: 20px; width: 300px;"
    />
    <el-button type="primary" @click="openAddDialog" style="margin-bottom: 20px;">新增医生</el-button>
    <el-table
      v-if="clinicsLoaded"
      :data="displayDoctors"
      style="width: 100%"
    >
      <el-table-column label="医生ID" prop="doctorId"  width="100">
      </el-table-column>
      <el-table-column prop="name" label="医生姓名" width="150"></el-table-column>
      <el-table-column prop="gender" label="性别" width="100"></el-table-column>
      <el-table-column prop="username" label="用户名" width="150"></el-table-column>
      <el-table-column prop="contactNumber" label="联系电话" width="150"></el-table-column>
      <el-table-column prop="title" label="职称" width="150"></el-table-column>
      <el-table-column prop="clinicName" label="科室" width="150"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="openUpdateDialog(scope.row)">更新</el-button>
          <el-button size="mini" type="danger" @click="deleteDoctor(scope.row.doctorId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      :page-size="pageSize"
      :total="totalDoctors"
      layout="total, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
    />
    <el-dialog v-model="dialogVisible" title="更新医生信息" width="400px">
      <el-form :model="currentDoctor" label-width="100px">
        <el-form-item label="医生姓名">
          <el-input v-model="currentDoctor.name" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="currentDoctor.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentDoctor.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="currentDoctor.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="职称">
          <el-input v-model="currentDoctor.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="currentDoctor.clinicId" placeholder="请选择科室">
            <el-option
              v-for="clinic in clinics"
              :key="clinic.clinicId"
              :label="clinic.clinicName"
              :value="clinic.clinicId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateDoctor(currentDoctor)">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增医生对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增医生" width="400px">
      <el-form :model="newDoctor" label-width="100px">
        <el-form-item label="医生姓名">
          <el-input v-model="newDoctor.name" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="newDoctor.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="newDoctor.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newDoctor.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="职称">
          <el-input v-model="newDoctor.title" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="newDoctor.clinicId" placeholder="请选择科室">
            <el-option
              v-for="clinic in clinics"
              :key="clinic.clinicId"
              :label="clinic.clinicName"
              :value="clinic.clinicId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDoctor">添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>